
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智慧农业边缘控制系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .header {
            background: rgba(255, 255, 255, 0.95);
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            color: #2c3e50;
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            color: #7f8c8d;
            font-size: 1.2em;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 20px;
        }
        
        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
            transition: transform 0.3s ease;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card h3 {
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            font-size: 1.3em;
        }
        
        .card h3::before {
            content: '🌱';
            margin-right: 10px;
            font-size: 1.5em;
        }
        
        .sensor-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .sensor-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #3498db;
        }
        
        .sensor-value {
            font-weight: bold;
            color: #2980b9;
            font-size: 1.1em;
        }
        
        .zone-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            margin: 10px 0;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #27ae60;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .btn.active {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }
        
        .pest-list {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .pest-item {
            padding: 12px;
            margin: 8px 0;
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            border-left: 4px solid #f39c12;
        }
        
        .status-active {
            color: #27ae60;
            font-weight: bold;
        }
        
        .status-inactive {
            color: #7f8c8d;
        }
        
        .analysis-section {
            margin: 15px 0;
            padding: 12px;
            background: #e8f5e8;
            border-radius: 8px;
            border-left: 4px solid #27ae60;
        }
        
        .loading {
            text-align: center;
            color: #7f8c8d;
            font-style: italic;
        }
        
        @media (max-width: 768px) {
            .container {
                grid-template-columns: 1fr;
                padding: 10px;
            }
            
            .sensor-grid {
                grid-template-columns: 1fr;
            }
            
            .zone-controls {
                flex-direction: column;
                gap: 10px;
            }
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9em;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🌱 智慧农业边缘控制系统</h1>
        <p>Smart Agriculture Edge Control System</p>
    </div>
    
    <div class="container">
        <!-- 传感器数据卡片 -->
        <div class="card">
            <h3>📡 实时传感器数据</h3>
            <div class="sensor-grid" id="sensorData">
                <div class="loading">正在加载数据...</div>
            </div>
        </div>
        
        <!-- 灌溉控制卡片 -->
        <div class="card">
            <h3>💧 灌溉控制系统</h3>
            <div id="irrigationControls">
                <div class="loading">正在加载控制面板...</div>
            </div>
        </div>
        
        <!-- 病虫害检测卡片 -->
        <div class="card">
            <h3>🐛 病虫害AI检测</h3>
            <button class="btn" onclick="runPestDetection()">🔍 执行AI检测</button>
            <div id="pestResults" class="pest-list">
                <div class="loading">暂无检测记录</div>
            </div>
        </div>
        
        <!-- 数据分析卡片 -->
        <div class="card">
            <h3>📊 智能分析报告</h3>
            <button class="btn" onclick="generateReport()">📈 生成分析报告</button>
            <div id="analysisReport">
                <div class="loading">点击按钮生成分析报告</div>
            </div>
        </div>
    </div>
    
    <div class="footer">
        <p>© 2025 智慧农业边缘控制系统 - 演示版本</p>
    </div>
    
    <script>
        // 获取传感器数据
        function updateSensorData() {
            fetch('/api/sensor_data')
                .then(response => response.json())
                .then(data => {
                    const sensorDiv = document.getElementById('sensorData');
                    sensorDiv.innerHTML = `
                        <div class="sensor-item">
                            <span>土壤湿度</span>
                            <span class="sensor-value">${data.soil_moisture?.toFixed(1)}%</span>
                        </div>
                        <div class="sensor-item">
                            <span>土壤温度</span>
                            <span class="sensor-value">${data.soil_temperature?.toFixed(1)}°C</span>
                        </div>
                        <div class="sensor-item">
                            <span>空气温度</span>
                            <span class="sensor-value">${data.air_temperature?.toFixed(1)}°C</span>
                        </div>
                        <div class="sensor-item">
                            <span>空气湿度</span>
                            <span class="sensor-value">${data.air_humidity?.toFixed(1)}%</span>
                        </div>
                        <div class="sensor-item">
                            <span>光照强度</span>
                            <span class="sensor-value">${data.light_intensity?.toFixed(0)} lux</span>
                        </div>
                        <div class="sensor-item">
                            <span>pH值</span>
                            <span class="sensor-value">${data.ph_value?.toFixed(2)}</span>
                        </div>
                        <div class="sensor-item">
                            <span>氮含量</span>
                            <span class="sensor-value">${data.nitrogen?.toFixed(1)} ppm</span>
                        </div>
                        <div class="sensor-item">
                            <span>磷含量</span>
                            <span class="sensor-value">${data.phosphorus?.toFixed(1)} ppm</span>
                        </div>
                    `;
                })
                .catch(error => {
                    console.error('获取传感器数据失败:', error);
                });
        }
        
        // 更新灌溉控制状态
        function updateIrrigationStatus() {
            fetch('/api/irrigation_status')
                .then(response => response.json())
                .then(data => {
                    const controlsDiv = document.getElementById('irrigationControls');
                    let html = '';
                    
                    Object.keys(data).forEach((zone, index) => {
                        const zoneData = data[zone];
                        const isActive = zoneData.active;
                        const statusClass = isActive ? 'status-active' : 'status-inactive';
                        const buttonText = isActive ? '停止灌溉' : '启动灌溉';
                        const buttonClass = isActive ? 'btn active' : 'btn';
                        
                        html += `
                            <div class="zone-controls">
                                <div>
                                    <strong>区域 ${index + 1}</strong><br>
                                    <span class="${statusClass}">
                                        ${isActive ? '运行中' : '停止'} 
                                        ${isActive ? `(${zoneData.flow_rate}L/min)` : ''}
                                    </span>
                                </div>
                                <button class="${buttonClass}" onclick="toggleIrrigation('${zone}', ${!isActive})">
                                    ${buttonText}
                                </button>
                            </div>
                        `;
                    });
                    
                    controlsDiv.innerHTML = html;
                })
                .catch(error => {
                    console.error('获取灌溉状态失败:', error);
                });
        }
        
        // 切换灌溉状态
        function toggleIrrigation(zoneId, start) {
            const action = start ? 'start' : 'stop';
            const payload = {
                zone_id: zoneId,
                action: action,
                flow_rate: 12,
                duration: 20
            };
            
            fetch('/api/irrigation_control', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateIrrigationStatus();
                }
            })
            .catch(error => {
                console.error('灌溉控制失败:', error);
            });
        }
        
        // 执行病虫害检测
        function runPestDetection() {
            fetch('/api/pest_detection', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                updatePestHistory();
            })
            .catch(error => {
                console.error('病虫害检测失败:', error);
            });
        }
        
        // 更新病虫害历史
        function updatePestHistory() {
            fetch('/api/pest_history')
                .then(response => response.json())
                .then(data => {
                    const pestDiv = document.getElementById('pestResults');
                    
                    if (data.history.length === 0) {
                        pestDiv.innerHTML = '<div class="loading">暂无检测记录</div>';
                        return;
                    }
                    
                    let html = '';
                    data.history.slice(-10).reverse().forEach(item => {
                        const time = new Date(item.timestamp).toLocaleTimeString();
                        html += `
                            <div class="pest-item">
                                <strong>${item.pest_type}</strong> - 
                                置信度: ${(item.confidence * 100).toFixed(1)}%<br>
                                <small>严重程度: ${item.severity} | ${time}</small><br>
                                <em>${item.recommendation}</em>
                            </div>
                        `;
                    });
                    
                    pestDiv.innerHTML = html;
                })
                .catch(error => {
                    console.error('获取病虫害历史失败:', error);
                });
        }
        
        // 生成分析报告
        function generateReport() {
            fetch('/api/analysis_report')
                .then(response => response.json())
                .then(data => {
                    const reportDiv = document.getElementById('analysisReport');
                    
                    if (data.error) {
                        reportDiv.innerHTML = `<div class="loading">${data.error}</div>`;
                        return;
                    }
                    
                    const time = new Date(data.timestamp).toLocaleString();
                    reportDiv.innerHTML = `
                        <div class="analysis-section">
                            <strong>📊 分析报告</strong><br>
                            <small>生成时间: ${time}</small>
                        </div>
                        <div class="analysis-section">
                            <strong>🌱 环境状态:</strong><br>
                            土壤状况: ${data.soil_status}<br>
                            温度状况: ${data.temperature_status}<br>
                            pH状况: ${data.ph_status}
                        </div>
                        <div class="analysis-section">
                            <strong>💧 灌溉建议:</strong><br>
                            ${data.irrigation_recommendation}
                        </div>
                        <div class="analysis-section">
                            <strong>🐛 病虫害风险:</strong><br>
                            风险等级: ${data.risk_level}
                        </div>
                    `;
                })
                .catch(error => {
                    console.error('生成分析报告失败:', error);
                });
        }
        
        // 定期更新数据
        function startUpdates() {
            updateSensorData();
            updateIrrigationStatus();
            updatePestHistory();
            
            // 每5秒更新一次
            setInterval(() => {
                updateSensorData();
                updateIrrigationStatus();
            }, 5000);
        }
        
        // 页面加载完成后开始更新
        document.addEventListener('DOMContentLoaded', function() {
            startUpdates();
        });
    </script>
</body>
</html>
    